<script setup lang="ts">
import { nextTick, ref } from 'vue';

import { useVbenModal } from '@vben/common-ui';

import { QRCode, Spin } from 'ant-design-vue';
import dayjs from 'dayjs';
import html2canvas from 'html2canvas';

import { downloadImage } from '#/utils/file/download';
// const emit = defineEmits<{ reload: [] }>();

const currModalTitle = ref<string>('查看二维码');
const currTitle = ref<string>('');
const currQrcodeUrl = ref<string>('');
const qrcodeRef = ref();
const captureRef = ref();

const [BasicModal, modalApi] = useVbenModal({
  class: 'w-[640px]',
  fullscreenButton: false,
  onClosed: handleClosed,
  onConfirm: handleConfirm,
  onOpenChange: async (isOpen) => {
    if (!isOpen) {
      return null;
    }
    modalApi.modalLoading(true);
    loading.value = true;
    const { modalTitle, title, qrcodeUrl } = modalApi.getData() as {
      modalTitle?: string;
      qrcodeUrl: string;
      title?: string;
    };
    if (modalTitle) {
      currModalTitle.value = modalTitle;
    }
    if (title) {
      currTitle.value = title;
    }
    currQrcodeUrl.value = qrcodeUrl;

    modalApi.modalLoading(false);
    loading.value = false;
  },
});

const loading = ref<boolean>(false);

async function handleConfirm() {
  try {
    modalApi.lock(true);
    await nextTick();
    if (!captureRef.value) return;

    const canvas = await html2canvas(captureRef.value, {
      backgroundColor: '#fff',
      scale: 2,
      useCORS: true,
    });
    // 转为 base64 图片
    const canvasImg = canvas.toDataURL('image/png');
    await downloadImage(
      canvasImg,
      `${currModalTitle.value}_${currTitle.value}_${dayjs().format('YYYYMMDDHHmmss')}`,
    );
    // modalApi.close();
  } catch (error) {
    console.error(error);
  } finally {
    modalApi.lock(false);
    loading.value = false;
  }
}

function reset() {
  currModalTitle.value = '';
  currTitle.value = '';
  currQrcodeUrl.value = '';
}

async function handleClosed() {
  reset();
}
</script>

<template>
  <BasicModal :title="currModalTitle" confirm-text="下载图片">
    <Spin :spinning="loading" tip="生成二维码中...">
      <div
        ref="captureRef"
        class="flex flex-col items-center justify-center py-[30px]"
      >
        <QRCode
          ref="qrcodeRef"
          :value="currQrcodeUrl"
          :bordered="false"
          :size="300"
        />
        <div v-if="currTitle" class="my-[10px] px-[15px] text-[18px]">
          {{ currTitle }}
        </div>
      </div>
    </Spin>
  </BasicModal>
</template>
